package com.adv.ems.filters.original.before;

import com.adv.ems.db.entity.CollectPointDO;
import com.adv.ems.enums.CollectPointStateEnum;
import com.adv.ems.enums.CollectPointWarningTypeEnum;
import com.adv.ems.enums.EnergyDataOriginal;
import com.adv.ems.filters.EnergyDataBaseFilter;
import com.adv.ems.filters.dto.FilterParam;
import com.adv.ems.filters.original.dto.EnergyDataOriginalBeforeDTO;
import com.adv.ems.manager.CollectPointManager;
import com.adv.ems.manager.EnergyDataOriginalManager;
import com.adv.ems.model.vo.ResultVO;
import com.adv.ems.service.WarningService;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class CollectPointCheckBeforeFilter extends EnergyDataBaseFilter<EnergyDataOriginalBeforeDTO, Boolean> {
    @Resource
    EnergyDataOriginalManager energyDataOriginalManager;
    @Resource
    CollectPointManager collectPointManager;
    @Resource
    WarningService warningService;

    @Override
    protected String getFilterName() {
        return "采集点状态校验";
    }

    @Override
    protected double getOrder() {
        return 0;
    }

    @Override
    protected boolean isBefore() {
        return true;
    }

    @Override
    protected String getType() {
        return EnergyDataOriginalBeforeDTO.class.getName();
    }

    @Override
    protected ResultVO<Boolean> handle(FilterParam<EnergyDataOriginalBeforeDTO> param) {
        List<EnergyDataOriginalBeforeDTO> fails = new ArrayList<>();
        for (EnergyDataOriginalBeforeDTO dto : param.getList()) {
            boolean check = check(dto);
            if (!check) {
                fails.add(dto);
            }
        }
        fails.forEach(f -> param.getList().remove(f));
        return ResultVO.success();
    }
    private boolean check(EnergyDataOriginalBeforeDTO d) {
        Map<Long, CollectPointDO> pointDOMap = collectPointManager.getAllMap();
        if (pointDOMap.get(d.getCollectPointId()) == null) {
            energyDataOriginalManager.updateDealState(d.getId(), d.getColDate(), EnergyDataOriginal.ERROR.name(), "采集点不存在");
            return false;
        }
        CollectPointDO point = pointDOMap.get(d.getCollectPointId());
        if (CollectPointStateEnum.REFUSE.name().equals(point.getState())) {
            energyDataOriginalManager.updateDealState(d.getId(), d.getColDate(), EnergyDataOriginal.ERROR.name(), "采集点状态【拒绝处理】");
            return false;
        }
        if (point.getDataType() == null) {
            String msg = "采集点对应的数据类型【累积/过程】未确定";
            energyDataOriginalManager.updateDealState(d.getId(), d.getColDate(), EnergyDataOriginal.ERROR.name(), msg);
            warningService.pushCollectPointWarning(null, point.getId(), CollectPointDO.class, CollectPointWarningTypeEnum.EXCEPTION_DATA, point.getDataType(), msg);
            return false;
        }
        return true;
    }
}
